package com.algorithm.recursion;

import java.util.Arrays;

/**
 * 递归插入排序
 */
public class E05InsertionSort {
    public static void sort(int a[]) {
        insertion(a, 1, a.length);
    }

    private static void insertion(int[] a, int low, int head) {
        if (low == head) {
            return;
        }
        int t = a[low]; //low为待排序左边界
        int i = low - 1; //i为已排序区域右边界
        while (i >= 0 && a[i] > t) {
            a[i + 1] = a[i];
            i--;
        }
        if (i + 1 != low) {
            a[i + 1] = t;
        }
        insertion(a, low + 1, head);
    }
    private static void insertion2(int[] a, int low, int head) {
        if (low == head) {
            return;
        }
        int i = low - 1; //i为已排序区域右边界
        while (i >= 0 && a[i] > a[i+1]) {
            int t = a[i+1];
            a[i + 1] = a[i];
            a[i]=t;
            i--;
        }
        insertion2(a, low + 1, head);
    }

    public static void main(String[] args) {
        int a[] = {1, 5, 5, 3, 2, 4, 9, 6};
        sort(a);
        System.out.println(Arrays.toString(a));//时间复杂度n+2
        int b[] = {1, 5, 5, 3, 2, 4, 9, 6};
        insertion2(b,1,b.length);
        System.out.println(Arrays.toString(b));//时间复杂度3n
    }

}
